from fastapi import APIRouter
from core.course_core import create_course, get_course_by_id, update_course, delete_course_by_id, count_users_in_course
from entity.schema.user_schema import CourseCreate, CourseUpdate, CourseOut
from exception.custom_exception import CustomErrorThrowException
from utils.base_response import BaseResponse

course = APIRouter()

@course.post("/add")
async def create_course_endpoint(course: CourseCreate):
    course_obj = await create_course(course)
    return BaseResponse(code=200, msg="success", data=course_obj)

@course.get("/info/{course_id}")
async def get_course(course_id: int):
    course = await get_course_by_id(course_id)
    if not course:
        raise CustomErrorThrowException(status_code=404, detail="Course not found")
    return BaseResponse(code=200, msg="success", data=course)

@course.put("/update/{course_id}")
async def update_course_endpoint(course_id: int, update: CourseUpdate):
    course = await update_course(course_id, update)
    if not course:
        raise CustomErrorThrowException(status_code=404, detail="Course not found")
    return BaseResponse(code=200, msg="success", data=course)

@course.delete("/del/{course_id}")
async def delete_course(course_id: int):
    success = await delete_course_by_id(course_id)
    if not success:
        raise CustomErrorThrowException(status_code=404, detail="Course not found")
    return BaseResponse(code=200, msg="Course deleted", data=None)

@course.get("/count/{course_id}")
async def count_users_in_course_endpoint(course_id: int):
    count = await count_users_in_course(course_id)
    return BaseResponse(code=200, msg="success", data={"count": count})